package com.taokatao.cardmee.common.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.taokatao.cardmee.R;

/**
 * Created by LY on 2016/12/27.
 */

public class RatioFrameLayout extends FrameLayout {
    int widthRatio;
    int heightRatio;

    public RatioFrameLayout(Context context) {
        this(context, null);
    }

    public RatioFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RatioFrameLayout);
        widthRatio = a.getInteger(R.styleable.RatioFrameLayout_widthRatio, 0);
        heightRatio = a.getInteger(R.styleable.RatioFrameLayout_heightRatio, 0);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (heightRatio != 0 && widthRatio != 0) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int mHeight = (int) (widthSize * 1f / widthRatio * heightRatio);

            measureChildren(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY)
                    , MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY));

            setMeasuredDimension(widthSize, mHeight);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
